package com.ctg.mainframe.sdk.utils;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.ctg.itrdc.cache.common.utils.PropertiesUtils;
import com.ctg.itrdc.cache.core.CacheService;
import com.ctg.itrdc.cache.core.ICacheService;
import com.ctg.itrdc.sysmgr.permission.core.CtgUser;
import com.ctg.itrdc.sysmgr.permission.core.IPermissionService;
import com.ctg.itrdc.sysmgr.permission.core.utils.AppContext;
import com.ctg.itrdc.sysmgr.permission.core.utils.WebUtils;
import com.ctg.mainframe.sdk.dto.SysMgrInfoDTO;

public class CacheHelper {
	
	private static final Logger logger = LoggerFactory.getLogger(CacheHelper.class);
	
	private static final String CACHE_PROPERTIES = "cache.properties";
	private static final String GROUP_MAINFRAME = "group.mainframe";
	
	private static final String PROV_COMMON_REGION_TYPE = "1100";
	private static final String LAN_COMMON_REGION_TYPE = "1300";
	private static final String PROV_LOC_TYPE = "11";
	private static final String CITY_LOC_TYPE = "12";
	private static final String COUNTRY_LOC_TYPE = "13";

	private static IPermissionService permissionService;

	static {
		// 读取缓存配置
		
		PropertiesUtils properties = PropertiesUtils.getInstance(CACHE_PROPERTIES);
		String result = properties.get(GROUP_MAINFRAME);
		
		if (StringUtils.isNotBlank(result))
			System.setProperty(GROUP_MAINFRAME, result);
		permissionService = AppContext.getContext().getBean(IPermissionService.class);
		
		System.out.println("############# System.getProperty: "  + System.getProperty(GROUP_MAINFRAME));
	}

	/**
	 * 设置分布式缓存。 key为sysUserId，需要依赖认证模块ctg-sysmgr-permission。 登录成功后，方可设置缓存。
	 * 
	 * @param dto
	 */
	public static void setSysMgrInfoCache(SysMgrInfoDTO dto) {
		CtgUser ctgUser = WebUtils.getCtgUser();
		if (ctgUser == null || ctgUser.getSysUserId() == null) {
			return;
		}
		setSysMgrInfoCache(ctgUser.getSysUserId() + "", preProcessSysMgrInfoDTO(dto));
	}

	/**
	 * 设置分布式缓存。
	 * 
	 * @param dto
	 */
	public static void setSysMgrInfoCache(String key, SysMgrInfoDTO dto) {
		String group = System.getProperty(GROUP_MAINFRAME);
		if (StringUtils.isBlank(group) || StringUtils.isBlank(key)) {
			return;
		}
		try {
			ICacheService cacheService = new CacheService(new String[] { group }, 15000);
			cacheService.set(group, key, JSON.toJSONString(dto));
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}
	
	/**
	 * 获取分布式缓存 key为sysUserId，需要依赖认证模块ctg-sysmgr-permission。 登录成功后，方可获取缓存。
	 * 
	 * @return
	 */
	public static SysMgrInfoDTO getSysMgrInfoCache() {
		logger.error("#####Start getSysMgrInfoCache()#####");
		logger.error("#####Before WebUtils.getCtgUser()");
		
		try {
			CtgUser ctgUser = WebUtils.getCtgUser();
			if (ctgUser == null || ctgUser.getSysUserId() == null) {
				logger.error("=========>ctgUser info: {}", ctgUser.toJSONString());
				return null;
			}
			
			logger.error("#####SysUserId From Seesion : {}", ctgUser.getSysUserId());

			return getSysMgrInfoCache(ctgUser.getSysUserId() + "");
		} catch (Exception e) {
			logger.info("获取ctgUser异常");
			return null;
		}
	}

	/**
	 * 获取分布式缓存
	 * 
	 * @return
	 */
	public static SysMgrInfoDTO getSysMgrInfoCache(String key) {
		String group = System.getProperty(GROUP_MAINFRAME);
		if (StringUtils.isBlank(group) || StringUtils.isBlank(key)) {
			return null;
		}
		try {
			ICacheService cacheService = new CacheService(new String[] { group }, 5000);
			String json = cacheService.get(group, key);
			logger.info("#####Get SysMgrInfo From Cache : {}", json);
			System.out.println("#####Get SysMgrInfo From Cache : " + json);
			return JSON.parseObject(json, SysMgrInfoDTO.class);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	private static SysMgrInfoDTO preProcessSysMgrInfoDTO(SysMgrInfoDTO sysMgrInfo) {

		CtgUser ctgUser = WebUtils.getCtgUser();
		if (null == ctgUser) {
			return null;
		}
		
		// 缓存写入系统用户信息
		sysMgrInfo.setSysUserId(null == ctgUser.getSysUserId() ? -1L : ctgUser.getSysUserId());
		sysMgrInfo.setSysUserCode(null == ctgUser.getSysUserCode() ? "" : ctgUser.getSysUserCode());
		
		// 缓存写入员工信息
		sysMgrInfo.setStaffId(null == ctgUser.getStaffId() ? -1L : ctgUser.getStaffId());
		sysMgrInfo.setStaffName(null == ctgUser.getStaffName() ? "" : ctgUser.getStaffName());
		
		// 缓存写入岗位信息
		Long sysPostId = sysMgrInfo.getSysPostId();
		Map<String, Object> post = permissionService.getPostById(sysPostId);
		if (null != post) {
			sysMgrInfo.setSysPostName(null == post.get("sys_post_name") ? "" : (String) post.get("sys_post_name"));
		}

		// 缓存写入岗位组织信息
		Map<String, Object> org = permissionService.getOrgByUserIdAndPostId(ctgUser.getSysUserId(), sysPostId);
		Long commonRegionId = null;
		if (null != org) {
			sysMgrInfo.setOrgName(null == org.get("org_name") ? "" : (String) org.get("org_name"));
			sysMgrInfo.setOrgId(null == org.get("org_id") ? -1L : (Long) org.get("org_id"));
			commonRegionId = (Long) org.get("common_region_id");
		}

		// 缓存写入用户所在区域信息
		if (null != commonRegionId) {
			sysMgrInfo.setCommonRegionId(commonRegionId);
			Map<String, Object> commonRegion = permissionService.getRegionNameById(commonRegionId);
			if (null != commonRegion)
				sysMgrInfo.setCommonRegionName(null == commonRegion.get("region_name") ? "" : (String) commonRegion.get("region_name"));
			else
				sysMgrInfo.setCommonRegionName("");
			
			// 缓存写入省级公共区域信息
			Long provCommonRegionId = -1L;
			Map<String, Object> provCommonRegion = permissionService.getParRegionByType(commonRegionId, PROV_COMMON_REGION_TYPE);
			if (null != provCommonRegion) {
				provCommonRegionId = (null == provCommonRegion.get("common_region_id")) ? -1L
						: (Long) provCommonRegion.get("common_region_id");
				sysMgrInfo.setProvCommonRegionId(provCommonRegionId);
				sysMgrInfo.setProvCommonRegionName(null == provCommonRegion.get("region_name") ? "" : (String) provCommonRegion.get("region_name"));

			} else {
				sysMgrInfo.setProvCommonRegionId(provCommonRegionId);
				sysMgrInfo.setProvCommonRegionName("");
			}
			
			// 缓存写入用户登录所在行政省份信息
			setProvince(sysMgrInfo, provCommonRegionId, commonRegionId);

			
			// 缓存写入本地网信息
			Map<String, Object> lan = permissionService.getParRegionByType(commonRegionId, LAN_COMMON_REGION_TYPE);
			Long lanId = -1L;
			if (null != lan) {
				lanId = (null == lan.get("common_region_id")) ? -1L : (Long) lan.get("common_region_id");
				sysMgrInfo.setLanId(lanId);
				sysMgrInfo.setLanName(null == lan.get("region_name") ? "" : (String) lan.get("region_name"));
			} else {
				sysMgrInfo.setLanId(lanId);
				sysMgrInfo.setLanName("");
			}
			
			// 缓存写入用户登录所在行政城市
			setCity(sysMgrInfo, lanId, commonRegionId);

		} else {
			sysMgrInfo.setCommonRegionId(-1L);
		}
		
		// 缓存写入用户登录所在行政县区
		setCountry(sysMgrInfo, commonRegionId);

		return sysMgrInfo;
	}

	/**
	 *  用户登录所在行政省份标识 
	 *  1. 如果provCommonRegionId !=-1,则根据provCommonRegionId取从表region_location_rel,
	 *     political_location获取political_location.loc_type=11的记录的loc_id; 
	 * 
	 *  2. 如果provCommonRegionId == -1,则根据commonRegionId取从表region_location_rel,
	 *     political_location获取political_location.loc_type=11的记录的loc_id;
	 * 
	 *  3. 如果上述不存在，则用-1标识
	 */
	private static void setProvince(SysMgrInfoDTO sysMgrInfo, Long provCommonRegionId, Long commonRegionId) {

		if (provCommonRegionId != -1) {
			List<Map<String, Object>> result = permissionService.getPoliticalLocation(provCommonRegionId, PROV_LOC_TYPE);
			if (null != result && result.size() > 0) {
				Map<String, Object> province = result.get(0);
				if (null != province) {
					sysMgrInfo.setProvinceId(null == province.get("loc_id") ? -1L : (Long) province.get("loc_id"));
					sysMgrInfo.setProvinceName(null == province.get("loc_name") ? "" : (String) province.get("loc_name"));
				}
			} else {
				sysMgrInfo.setProvinceId(-1L);
				sysMgrInfo.setProvinceName("");
			}
		} else if (provCommonRegionId == -1) {
			List<Map<String, Object>> result = permissionService.getPoliticalLocation(commonRegionId, PROV_LOC_TYPE);
			if (null != result && result.size() > 0) {
				Map<String, Object> province = result.get(0);
				if (null != province) {
					sysMgrInfo.setProvinceId(null == province.get("loc_id") ? -1L : (Long) province.get("loc_id"));
					sysMgrInfo.setProvinceName(null == province.get("loc_name") ? "" : (String) province.get("loc_name"));
				}
			} else {
				sysMgrInfo.setProvinceId(-1L);
				sysMgrInfo.setProvinceName("");
			}
		} else {
			sysMgrInfo.setProvinceId(-1L);
			sysMgrInfo.setProvinceName("");
		}
	}
	
	/**
	 *  用户登录所在行政城市标识
	 *  1. 如果lanId != -1,则根据lanId取从表region_location_rel,political_location获取political_location.loc_type=12的记录的loc_id;
	 *  2. 如果lanId == -1,则根据commonRegionId取从表region_location_rel,political_location获取political_location.loc_type=12的记录的loc_id;
	 *  3. 如果上述不存在，则用-1标识
	 */
	private static void setCity (SysMgrInfoDTO sysMgrInfo, Long lanId, Long commonRegionId) {
		if (lanId != -1) {
			List<Map<String, Object>> result = permissionService.getPoliticalLocation(lanId, CITY_LOC_TYPE);
			if (null != result && result.size() > 0) {
				Map<String, Object> city = result.get(0);
				if (null != city) {
					sysMgrInfo.setCityId(null == city.get("loc_id") ? -1L : (Long) city.get("loc_id"));
					sysMgrInfo.setCityName(null == city.get("loc_name") ? "" : (String) city.get("loc_name"));
				}
			} else {
				sysMgrInfo.setCityId(-1L);
				sysMgrInfo.setCityName("");
			}
		} else if (lanId == -1) {
			List<Map<String, Object>> result = permissionService.getPoliticalLocation(commonRegionId, CITY_LOC_TYPE);
			if (null != result && result.size() > 0) {
				Map<String, Object> city = result.get(0);
				if (null != city) {
					sysMgrInfo.setCityId(null == city.get("loc_id") ? -1L : (Long) city.get("loc_id"));
					sysMgrInfo.setCityName(null == city.get("loc_name") ? "" : (String) city.get("loc_name"));
				}
			} else {
				sysMgrInfo.setCityId(-1L);
				sysMgrInfo.setCityName("");
			}
		} else {
			sysMgrInfo.setCityId(-1L);
			sysMgrInfo.setCityName("");
		}
	}
	
	
	/**
	 *  用户登录所在行政县区标识
  	 *  1. 根据commonRegionId取从表region_location_rel,political_location获取political_location.loc_type=13的记录的loc_id;
  	 *  2. 如果上述不存在，则用-1标识
  	 */
	private static void setCountry (SysMgrInfoDTO sysMgrInfo, Long commonRegionId) {
		if (commonRegionId != -1) {
			List<Map<String, Object>> result = permissionService.getPoliticalLocation(commonRegionId, COUNTRY_LOC_TYPE);
			if (null != result && result.size() > 0) {
				Map<String, Object> country = result.get(0);
				if (null != country) {
					sysMgrInfo.setCountyId(null == country.get("loc_id") ? -1L : (Long) country.get("loc_id"));
					sysMgrInfo.setCountyName(null == country.get("loc_name") ? "" : (String) country.get("loc_name"));
				}
			} else {
				sysMgrInfo.setCountyId(-1L);
				sysMgrInfo.setCountyName("");
			}
		} else {
			sysMgrInfo.setCountyId(-1L);
			sysMgrInfo.setCountyName("");
		}
	}
}
